/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package com.company.workflow.loader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.opensymphony.workflow.InvalidWorkflowDescriptorException;
import com.opensymphony.workflow.loader.ConditionalResultDescriptor;
import com.opensymphony.workflow.loader.ValidationHelper;
import com.opensymphony.workflow.util.Validatable;


/**
 * @author <a href="mailto:plightbo@hotmail.com">Pat Lightbody</a>
 * @version $Revision: 1.17 $
 */
public class StepDescriptor extends AbstractDescriptor implements Validatable {
    //~ Instance fields ////////////////////////////////////////////////////////

    protected List actions = new ArrayList();

    /**
     * this list maintained internally to allow for proper xml serialization.
     * All common-action elements in the XML file are expanded into ActionDescriptors
     * and are available via getActions()
     */
    protected List commonActions = new ArrayList();
    protected List permissions = new ArrayList();
    protected List postFunctions = new ArrayList();
    protected List preFunctions = new ArrayList();
    protected Map metaAttributes = new HashMap();
    protected String name;
    protected boolean hasActions = false;

    //~ Constructors ///////////////////////////////////////////////////////////

    public StepDescriptor() {
    }


    //~ Methods ////////////////////////////////////////////////////////////////

    public ActionDescriptor getAction(int id) {
        for (Iterator iterator = actions.iterator(); iterator.hasNext();) {
            ActionDescriptor action = (ActionDescriptor) iterator.next();

            if (action.getId() == id) {
                return action;
            }
        }

        return null;
    }

    /**
     * Get a List of {@link ActionDescriptor}s for this step
     */
    public List getActions() {
        return actions;
    }

    public void setMetaAttributes(Map metaAttributes) {
        this.metaAttributes = metaAttributes;
    }

    public Map getMetaAttributes() {
        return metaAttributes;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    /**
     * Get a List of {@link PermissionDescriptor}s for this step
     */
    public List getPermissions() {
        return permissions;
    }

    public void setPostFunctions(List postFunctions) {
        this.postFunctions = postFunctions;
    }

    public List getPostFunctions() {
        return postFunctions;
    }

    public void setPreFunctions(List preFunctions) {
        this.preFunctions = preFunctions;
    }

    public List getPreFunctions() {
        return preFunctions;
    }

    public boolean resultsInJoin(int join) {
        for (Iterator iterator = actions.iterator(); iterator.hasNext();) {
            ActionDescriptor actionDescriptor = (ActionDescriptor) iterator.next();

            if (actionDescriptor.getUnconditionalResult().getJoin() == join) {
                return true;
            }

            List results = actionDescriptor.getConditionalResults();

            for (Iterator iterator2 = results.iterator(); iterator2.hasNext();) {
                ConditionalResultDescriptor resultDescriptor = (ConditionalResultDescriptor) iterator2.next();

                if (resultDescriptor.getJoin() == join) {
                    return true;
                }
            }
        }

        return false;
    }

    public void validate() throws InvalidWorkflowDescriptorException {
        if ((commonActions.size() == 0) && (actions.size() == 0) && hasActions) {
            throw new InvalidWorkflowDescriptorException("Step '" + name + "' actions element must contain at least one action or common-action");
        }

        if (getId() == -1) {
            throw new InvalidWorkflowDescriptorException("Cannot use a step ID of -1 as it is a reserved value");
        }

        ValidationHelper.validate(actions);
        ValidationHelper.validate(permissions);
        ValidationHelper.validate(preFunctions);
        ValidationHelper.validate(postFunctions);

        Iterator iter = commonActions.iterator();

        while (iter.hasNext()) {
            Object o = iter.next();

            try {
                Integer actionId = new Integer(o.toString());
                ActionDescriptor commonActionReference = (ActionDescriptor) ((WorkflowDescriptor) getParent()).getCommonActions().get(actionId);

                if (commonActionReference == null) {
                    throw new InvalidWorkflowDescriptorException("Common action " + actionId + " specified in step " + getName() + " does not exist");
                }
            } catch (NumberFormatException ex) {
                throw new InvalidWorkflowDescriptorException("Common action " + o + " is not a valid action ID");
            }
        }
    }



 

	public String getXML()
	{
		StringBuffer buf = new StringBuffer();
        buf.append("<step id=\"" + getId() + "\"");

        if ((name != null) && (name.length() > 0)) {
        	buf.append(" name=\"" + name + "\"");
        }

        buf.append(">");

        Iterator iter = metaAttributes.entrySet().iterator();

        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            buf.append("<meta name=\"");
            buf.append(entry.getKey());
            buf.append("\">");
            buf.append(entry.getValue());
            buf.append("</meta>");
        }

        if (preFunctions.size() > 0) {
            
            buf.append("<pre-functions>");

            for (int i = 0; i < preFunctions.size(); i++) {
                FunctionDescriptor function = (FunctionDescriptor) preFunctions.get(i);
                buf.append(function.getXML());
            }

            buf.append("</pre-functions>");
        }

        if (permissions.size() > 0) {
            
            buf.append("<external-permissions>");

            for (int i = 0; i < permissions.size(); i++) {
                PermissionDescriptor permission = (PermissionDescriptor) permissions.get(i);
                buf.append(permission.getXML());
            }

            buf.append("</external-permissions>");
        }

        if ((actions.size() > 0) || (commonActions.size() > 0)) {
            
            buf.append("<actions>");

            // special serialization common-action elements
            for (int i = 0; i < commonActions.size(); i++) {
                buf.append("<common-action id=\"" + commonActions.get(i) + "\" />");
            }

            for (int i = 0; i < actions.size(); i++) {
                ActionDescriptor action = (ActionDescriptor) actions.get(i);
                buf.append(action.getXML());
            }

            buf.append("</actions>");
        }

        if (postFunctions.size() > 0) {
            
            buf.append("<post-functions>");

            for (int i = 0; i < postFunctions.size(); i++) {
                FunctionDescriptor function = (FunctionDescriptor) postFunctions.get(i);
                buf.append(function.getXML());
            }

            buf.append("</post-functions>");
        }

        buf.append("</step>");
        return buf.toString();
	}
}
